package cn.itsource.common.util;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.itsource.common.domain.BaiduAiDto;
import cn.itsource.common.exception.BusinessException;
import lombok.SneakyThrows;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class BaiduAiUtil {
    private static final String API_KEY = "i0PfyhsZ24Igt9szywKYZ52j";
    private static final String SECRET_KEY = "2e9Sz4ayOfje3jpPWN00eN8UISgA39KC";
    private static final String ACCESS_URL = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s";
    /**
     * 重要提示代码中所需工具类
     * FileUtil,Base64Util,HttpUtil,GsonUtils请从
     * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
     * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
     * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
     * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
     * 下载
     */
    @SneakyThrows
    public static void TextCensor(String message) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined";
        try {
            String param = "text=" + URLEncoder.encode(message, "utf-8");

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = getAccessToken();

            String result = HttpUtil.post(url, accessToken, param);
            System.out.println(result);
            JSONObject jsonObject = JSONUtil.parseObj(result);
            Object conclusion = jsonObject.get("conclusion");
            if(conclusion == null){
                throw new BusinessException("服务器异常请稍后重试");
            }
            if("不合规".equals(conclusion.toString())){
                BaiduAiDto baiduAiDto = com.alibaba.fastjson.JSONObject.parseObject(result, BaiduAiDto.class);
                BaiduAiDto.BaiduAiDtoData baiduAiDtoData = baiduAiDto.getData().get(0);
                throw new BusinessException("您输入"+message+"存在这个问题:"+baiduAiDtoData.getMsg());
            }
        }  catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        BaiduAiUtil.TextCensor("我草拟吗");
    }

    public static String getAccessToken(){
        try {
            //得到地址
            String format_url = String.format(ACCESS_URL, API_KEY, SECRET_KEY);
            //发送请求获取tocken
            String post = cn.hutool.http.HttpUtil.get(format_url);
            //得到结果
            JSONObject jsonObject = JSONUtil.parseObj(post);//这个方法的作用是 将json数据转换为一个jsonObject(有点类似于hashmap)
            return jsonObject.get("access_token").toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
